package com.huan.study.mybatis.controller;

import com.huan.study.mybatis.entity.Customer;
import com.huan.study.mybatis.mappers.CustomerMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author huan.fu 2021/5/18 - 上午10:51
 */
@RestController
public class CustomerController {

    private static final Logger log = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private CustomerMapper customerMapper;

    @GetMapping("printSql")
    public String printSql() {
        // 测试各种方法
        testInsert();
        testSelectById();
        testSelectByPhone();
        testUpdate();
        testConditionQuery();
        testBatchOperations();
        testDelete();

        log.info("\n=== 所有测试完成 ===");
        return "更新成功";
    }


    /**
     * 测试插入操作
     */
    private void testInsert() {
        log.info("\n1. 测试插入操作:");

        Customer customer = new Customer();
        customer.setPhone("13800138001");
        customer.setAddress("北京市朝阳区");
        customer.setAge(25);
        customer.setCreateTime(new Date());
        customer.setTriggerDate(new Date());
        customer.setRegisterDate(new Date());

        try {
            int result = customerMapper.insert(customer);

            log.info("   - 单条插入: 影响行数 = " + result + ", 生成ID = " + customer.getId());
        } catch (Exception e) {
            log.info("   - 单条插入异常: " + e.getMessage());
        }
    }

    /**
     * 测试根据ID查询
     */
    private void testSelectById() {
        log.info("\n2. 测试根据ID查询:");

        try {
            Customer customer = customerMapper.selectById(1L);
            if (customer != null) {
                log.info("   - 根据ID查询成功: " + customer.getPhone() + ", " + customer.getAddress());
            } else {
                log.info("   - 根据ID查询: 记录不存在");
            }
        } catch (Exception e) {
            log.info("   - 根据ID查询异常: " + e.getMessage());
        }
    }

    /**
     * 测试根据手机号查询
     */
    private void testSelectByPhone() {
        log.info("\n3. 测试根据手机号查询:");

        try {
            Customer customer = customerMapper.selectByPhone("13800138001");
            if (customer != null) {
                log.info("   - 根据手机号查询成功: " + customer.getPhone() + ", 年龄=" + customer.getAge());
            } else {
                log.info("   - 根据手机号查询: 记录不存在");
            }
        } catch (Exception e) {
            log.info("   - 根据手机号查询异常: " + e.getMessage());
        }
    }

    /**
     * 测试更新操作
     */
    private void testUpdate() {
        log.info("\n4. 测试更新操作:");

        try {
            // 先查询一条记录
            Customer customer = customerMapper.selectByPhone("13800138001");
            if (customer != null) {
                customer.setAddress("上海市浦东新区");
                customer.setAge(26);

                int result = customerMapper.updateById(customer);

                log.info("   - 更新操作: 影响行数 = " + result);

                // 测试选择性更新
                Customer partialUpdate = new Customer();
                partialUpdate.setId(customer.getId());
                partialUpdate.setAge(27);

                int selectiveResult = customerMapper.updateSelectiveById(partialUpdate);

                log.info("   - 选择性更新: 影响行数 = " + selectiveResult);
            }
        } catch (Exception e) {
            log.info("   - 更新操作异常: " + e.getMessage());
        }
    }

    /**
     * 测试条件查询
     */
    private void testConditionQuery() {
        log.info("\n5. 测试条件查询:");

        try {
            Map<String, Object> condition = new HashMap<>();
            condition.put("minAge", 20);
            condition.put("maxAge", 30);
            condition.put("phone", "138");

            List<Customer> customers = customerMapper.selectByCondition(condition);
            log.info("   - 条件查询: 找到 " + customers.size() + " 条记录");

            // 测试分页查询
            Map<String, Object> pageParams = new HashMap<>();
            pageParams.put("offset", 0);
            pageParams.put("pageSize", 10);
            Map<String, Object> pageCondition = new HashMap<>();
            pageCondition.put("minAge", 20);
            pageParams.put("condition", pageCondition);

            List<Customer> pageResult = customerMapper.selectByPage(pageParams);
            log.info("   - 分页查询: 返回 " + pageResult.size() + " 条记录");

            // 测试统计
            Long count = customerMapper.countByCondition(condition);
            log.info("   - 统计查询: 总数 = " + count);

        } catch (Exception e) {
            log.info("   - 条件查询异常: " + e.getMessage());
        }
    }

    /**
     * 测试批量操作
     */
    private void testBatchOperations() {
        log.info("\n6. 测试批量操作:");

        try {
            // 批量插入
            List<Customer> batchCustomers = new ArrayList<>();
            for (int i = 2; i <= 5; i++) {
                Customer customer = new Customer();
                customer.setPhone("1380013800" + i);
                customer.setAddress("测试地址" + i);
                customer.setAge(20 + i);
                customer.setCreateTime(new Date());
                customer.setTriggerDate(new Date());
                customer.setRegisterDate(new Date());
                batchCustomers.add(customer);
            }

            int batchInsertResult = customerMapper.batchInsert(batchCustomers);

            log.info("   - 批量插入: 影响行数 = " + batchInsertResult);

            // 批量更新（需要先有数据）
            List<Customer> updateList = new ArrayList<>();
            List<Customer> existingCustomers = customerMapper.selectByCondition(new HashMap<>());
            if (existingCustomers.size() >= 2) {
                for (int i = 0; i < Math.min(2, existingCustomers.size()); i++) {
                    Customer customer = existingCustomers.get(i);
                    customer.setAddress("更新后的地址" + i);
                    updateList.add(customer);
                }

                int batchUpdateResult = customerMapper.batchUpdate(updateList);

                log.info("   - 批量更新: 影响行数 = " + batchUpdateResult);
            }

        } catch (Exception e) {
            log.info("   - 批量操作异常: " + e.getMessage());
        }
    }

    /**
     * 测试删除操作
     */
    private void testDelete() {
        log.info("\n7. 测试删除操作:");

        try {
            // 先插入一条测试数据用于删除
            Customer testCustomer = new Customer();
            testCustomer.setPhone("13900139001");
            testCustomer.setAddress("删除测试地址");
            testCustomer.setAge(30);
            testCustomer.setCreateTime(new Date());
            testCustomer.setTriggerDate(new Date());
            testCustomer.setRegisterDate(new Date());

            customerMapper.insert(testCustomer);

            log.info("   - 插入测试数据成功，ID = " + testCustomer.getId());

            // 根据ID删除
            int deleteResult = customerMapper.deleteById(testCustomer.getId());

            log.info("   - 根据ID删除: 影响行数 = " + deleteResult);

            // 根据手机号删除
            int deleteByPhoneResult = customerMapper.deleteByPhone("13800138002");

            log.info("   - 根据手机号删除: 影响行数 = " + deleteByPhoneResult);

            // 批量删除
            List<Long> idsToDelete = Arrays.asList(3L, 4L, 5L);
            int batchDeleteResult = customerMapper.batchDelete(idsToDelete);

            log.info("   - 批量删除: 影响行数 = " + batchDeleteResult);

        } catch (Exception e) {
            log.info("   - 删除操作异常: " + e.getMessage());
        }
    }
}
